package com.xhj.sportsnews.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.xhj.sportsnews.R;
import com.xhj.sportsnews.adapter.HeadFragmentAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class HeadineFragment extends Fragment implements View.OnClickListener, ViewPager.OnPageChangeListener, View.OnTouchListener {


    private RadioButton headbtn01;
    private RadioButton headbtn02;
    private List<Fragment> list;
    private ViewPager viewPager;
    private RadioGroup radioGroup;

    public HeadineFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_headine, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        radioGroup = ((RadioGroup) view.findViewById(R.id.head_radiogroup));
        viewPager = ((ViewPager) view.findViewById(R.id.head_viewPager));
        headbtn01 = ((RadioButton) view.findViewById(R.id.head_btn01));
        headbtn02 = ((RadioButton) view.findViewById(R.id.head_btn02));
        headbtn01.setOnClickListener(this);
        headbtn02.setOnClickListener(this);

        list = new ArrayList<>();
        list.add(new HeadLeftFragment());
        list.add(new HeadRightFragment());

        HeadFragmentAdapter adapter = new HeadFragmentAdapter(getFragmentManager(), list, getContext());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(this);
        viewPager.setOnTouchListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.head_btn01:
                viewPager.setCurrentItem(0);
                break;
            case R.id.head_btn02:
                viewPager.setCurrentItem(1);
                break;
        }

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        ((RadioButton) radioGroup.getChildAt(position)).setChecked(true);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (motionEvent.getX() > 0) {
                    viewPager.requestDisallowInterceptTouchEvent(true);
                }
                break;
        }
        return false;
    }
}
